import { useCallback, useEffect, useMemo, useState } from 'react';
import Taro, { useRouter, usePullDownRefresh } from '@tarojs/taro';
import { useCountDown, useRequest } from 'ahooks';
import { QRCode as TaroQRCode } from 'taro-code';
import { useInitStore } from '@/common/hox/initStore';
import classNames from 'classnames';
import { Image, Swiper, SwiperItem } from '@tarojs/components';
import dayjs from 'dayjs';
import { getSubDesc } from '@/common/utils';
import { Loading } from '@/components';
import appConfig from '@/utils/appConfig';
import { TicketModeMap } from '@/utils/enum';
import { useUserStore } from '@/common/hox/userStore';
import { CustomNavBar } from '@/components';
import { getOrderDetailByCoupon, getOrderDetail, orderCancel } from '@/service';
import { Refund, Location, ToPay, Trash, Shopping } from '@nutui/icons-react-taro';
import styles from './index.module.less';
interface Take {
    // Add properties according to your needs
    id: string;
    // Add other properties...
}

interface MovieOrderDetail {
    movieName: string;
    id: string;
    orderNo: string;
    takes: Take[];
    purchaseMerchantId: number;
    appId: number;
    appType: number;
    userId: number;
    userMobile: string | null;
    mobile: string | null;
    movieCityId: number;
    longitude: number;
    ticketInfos: any[];
    actualSeatInfos: any[];
    latitude: number;
    cinemaName: string;
    cinemaAddress: string;
    showTime: string;
    version?: string;
    hall: string;
    seatInfos: any[];
    posterUrl: string;
    orderStatus: number;
    fastTicket: string;
    orderStatusDesc: string;
    sellerWords: string;
    orderTime: string;
    paymentTotal: string;
    switchSeat: string;
    totalPrice: string;
}

type OrderDetailPagePropsType = {
    pay: (orderDetail: Movie.Order.MovieOrderResponse) => Promise<void | false>;
};

type RouterParamType = {
    orderNo?: string;
} & {
    couponCode?: string;
};

const allowKeyList = [
    '售罄',
    '未找到',
    '必选商品',
    '当前场次已停售',
    '请稍后再试',
    '已存在相同场次',
    '座位旁边不要留空',
    '用户主动取消',
];

const blockKeyList = ['#'];

const OrderDetailPage = (props: OrderDetailPagePropsType) => {
    const { pay } = props;
    const { params } = useRouter<RouterParamType>();
    const { orderNo, couponCode } = params;
    const { initReady } = useInitStore();
    const { userInfo, token } = useUserStore();
    const [pollingInterval, setPollingInterval] = useState(3000);
    const [codeCurrentIndex, setCodeCurrentIndex] = useState(0);
    useEffect(() => {
        if (!orderNo && !couponCode) {
            Taro.showModal({
                title: '错误',
                content: '缺少订单号或券码',
                showCancel: false,
                confirmText: '我知道了',
            });
        }
        if (orderNo && token === false) {
            Taro.showModal({
                title: '错误',
                content: '请登录后查看',
                showCancel: false,
                confirmText: '我知道了',
            });
        }
    }, [orderNo, couponCode, token]);

    // 获取订单详情数据
    const getOrderDetailApi = useRequest(
        async () => {
            if (couponCode) return getOrderDetailByCoupon(couponCode);
            return getOrderDetail(orderNo as string);
        },
        {
            ready: Boolean(initReady && (couponCode || (orderNo && userInfo?.userId))),
            pollingInterval,
            onSuccess: (res) => {
                setPollingInterval(3000);
                if (res.orderStatus >= 4) {
                    getOrderDetailApi.cancel();
                }
            },
        }
    );

    // 取消订单
    const orderCancelApi = useRequest(orderCancel, {
        manual: true,
        onSuccess: () => getOrderDetailApi.refresh(),
    });

    const [_number, { minutes, seconds }] = useCountDown({
        targetDate: dayjs(getOrderDetailApi.data?.orderExpireTime).format('YYYY-MM-DD HH:mm:ss'),
        onEnd: () => getOrderDetailApi.refresh(),
    });

    //
    const showRemark = useMemo(() => {
        const sellerWords = getOrderDetailApi.data?.sellerWords;
        if (sellerWords) {
            const hasKey = !!allowKeyList.find((key) => sellerWords.includes(key));
            const cannotHasKey = !!blockKeyList.find((key) => sellerWords.includes(key));
            return !cannotHasKey && hasKey;
        }
        return false;
    }, [getOrderDetailApi.data]);

    const { ticketInfos, actualSeatInfos, ...detail } =
        (getOrderDetailApi.data as unknown as MovieOrderDetail) || {};

    const payment = useCallback(async () => {
        if (getOrderDetailApi.data) {
            const res = await pay(getOrderDetailApi.data);
            if (res === false) return;
            getOrderDetailApi.refresh();
        }
    }, [getOrderDetailApi.data]);

    // 下拉刷新
    usePullDownRefresh(async () => {
        await getOrderDetailApi?.runAsync();
        Taro.stopPullDownRefresh();
    });
    if (!getOrderDetailApi.data) return <Loading />
    return (
        <div className={styles.orderPage}>
            <CustomNavBar title={'订单详情'} />
            {/* 票据头部 */}
            <div className={classNames(styles.card, styles.movieInfo)}>
                <div className={styles.header}>
                    <div
                        className={styles.store}
                        onClick={() => {
                            detail.latitude !== null &&
                                Taro.openLocation({
                                    latitude: detail.latitude,
                                    longitude: detail.longitude,
                                    scale: 18,
                                });
                        }}
                    >
                        <div className={styles.name}>{detail.cinemaName}</div>
                        <div className={styles.address}>
                            <Location color="var(--color-main)" className={styles.addressIcon} />
                            {detail.cinemaAddress}
                        </div>
                    </div>
                </div>
                <div className={styles.detail}>
                    <div className={styles.text}>
                        <div className={styles.movieName}>{detail.movieName}</div>
                        <div className={styles.showTime}>
                            {getSubDesc(detail.showTime, true)}
                            <span className={styles.black}>
                                {dayjs(detail.showTime).format('HH:mm')} 开场&nbsp;
                            </span>
                            {detail?.version ? decodeURIComponent(detail?.version) : null}
                        </div>
                        <div className={styles.hallName}>{detail.hall}</div>
                        <div className={styles.seatList}>
                            {detail?.seatInfos &&
                                detail?.seatInfos.length &&
                                detail?.seatInfos.map((item) => {
                                    const { seatName } = item;
                                    return (
                                        <div className={styles.seatItem} key={seatName}>
                                            {' '}
                                            {seatName}{' '}
                                        </div>
                                    );
                                })}
                        </div>
                    </div>
                    <Image className={styles.pic} src={detail.posterUrl} mode="aspectFill" />
                </div>
            </div>
            {/* 待支付 */}
            {detail.orderStatus === 1 && (
                <div className={classNames(styles.card, styles.statusCard)}>
                    <div className={styles.header}>待支付</div>
                    <div className={styles.countDown}>
                        <span className={styles.colorMain}>
                            {minutes >= 10 ? minutes : `0${minutes}`}:
                            {seconds >= 10 ? seconds : `0${seconds} `}
                        </span>
                        后将自动取消
                    </div>
                    <ToPay color="var(--color-main)" className={styles.statusImage} size="60px" />
                    {/* <Image className={styles.statusImage} mode='aspectFit' src='https://fulu-media.oss-cn-hangzhou.aliyuncs.com/public/chupiaoji.gif' /> */}
                    <div className={styles.remarkText}>请尽快完成付款，晚了就没座位了哦~</div>
                    <div className={styles.cardBtnList}>
                        <div
                            className={classNames(styles.cardBtn, styles.weak)}
                            onClick={() => {
                                Taro.showModal({
                                    title: '取消订单',
                                    content: '确定取消订单？',
                                    cancelText: '我再想想',
                                    success: (res) =>
                                        res.confirm && orderCancelApi.run({ orderNo: detail.id }),
                                });
                            }}
                        >
                            取消
                        </div>
                        <div className={classNames(styles.cardBtn, styles.main)} onClick={payment}>
                            立即支付
                        </div>
                    </div>
                </div>
            )}
            {/* 待出票 出票中 */}
            {[2, 3, 4].includes(detail.orderStatus) && (
                <div className={classNames(styles.card, styles.statusCard)}>
                    <div className={styles.header}>出票中</div>
                    {/* <Notepad color="var(--color-main)" className={styles.statusImage} size="60px" /> */}
                    <Shopping
                        color="var(--color-main)"
                        className={styles.statusImage}
                        size="60px"
                    />
                    <div className={styles.remarkText}>
                        请稍等，支付成功后{detail.fastTicket ? '15' : '15~50'}分钟内自动出票
                    </div>
                    <div className={styles.cardBtnList}>
                        <div
                            className={classNames(styles.cardBtn, styles.main)}
                            onClick={appConfig.toService}
                        >
                            联系客服
                        </div>
                    </div>
                </div>
            )}
            {/* 已出票 */}
            {[5].includes(detail.orderStatus) && (
                <div className={classNames(styles.card, styles.statusCard)}>
                    <div className={styles.header}>
                        取票码
                        <div>
                            <span className={styles.colorMain}>{codeCurrentIndex + 1}</span>
                            {' / '}
                            {ticketInfos.length} 张
                        </div>
                    </div>
                    <div className={styles.codeSwiperContainer}>
                        <Swiper
                            className={styles.codeSwiper}
                            indicatorDots={false}
                            current={codeCurrentIndex}
                            autoplay={false}
                            onChange={(e) => setCodeCurrentIndex(e.detail.current)}
                            full
                        >
                            {ticketInfos.map((item, index) => {
                                const { takeCode } = item;
                                const splitNum = (str: string) =>
                                    str?.replace(/\s/g, '')?.replace(/(.{4})/g, '$1 ');
                                const codeArray = takeCode
                                    ?.split('|')
                                    .map((item) => splitNum(item));

                                let actualSeatInfo = '';
                                if (actualSeatInfos.length > 0) {
                                    actualSeatInfos.map((seat, index1) => {
                                        actualSeatInfo += detail.seatInfos.some(
                                            (item) => item.seatName === seat.seatName
                                        )
                                            ? ''
                                            : seat.seatName + '；';
                                    });
                                }
                                return (
                                    <SwiperItem key={index}>
                                        <div className={styles.takeCodeItem}>
                                            <TaroQRCode
                                                size={130}
                                                text={takeCode}
                                                className={styles.takeCodeItemCode}
                                            />
                                            <div className={styles.remarkText}>
                                                若二维码无法使用
                                            </div>
                                            <div className={styles.remarkText}>
                                                输入
                                                <span className={styles.colorBlack}>取票码</span>
                                                自助取票或
                                                <span className={styles.colorBlack}>
                                                    联系影院前台
                                                </span>
                                            </div>
                                            {actualSeatInfos.length > 0 &&
                                                actualSeatInfo !== '' && (
                                                    <div className={styles.remarkText}>
                                                        <span className={styles.colorBlack}>
                                                            座位已变更为：
                                                        </span>
                                                        <span className={styles.colorMain}>
                                                            {actualSeatInfo}
                                                        </span>
                                                    </div>
                                                )}
                                            <div className={styles.remarkText}>
                                                {codeArray.length === 1 ? (
                                                    <div
                                                        className={styles.codeText}
                                                        onClick={() => {
                                                            Taro.setClipboardData({
                                                                data: codeArray[0],
                                                                success: function () {
                                                                    Taro.showToast({
                                                                        title: '取票码复制成功',
                                                                        icon: 'success',
                                                                    });
                                                                },
                                                            });
                                                        }}
                                                    >
                                                        取票码: {codeArray[0]}
                                                    </div>
                                                ) : (
                                                    <>
                                                        <div
                                                            className={styles.codeText}
                                                            onClick={() => {
                                                                Taro.setClipboardData({
                                                                    data: codeArray[0],
                                                                    success: function () {
                                                                        Taro.showToast({
                                                                            title: '取票码复制成功',
                                                                            icon: 'success',
                                                                        });
                                                                    },
                                                                });
                                                            }}
                                                        >
                                                            取票码: {codeArray[0]}
                                                        </div>

                                                        <div
                                                            className={styles.codeText}
                                                            onClick={() => {
                                                                Taro.setClipboardData({
                                                                    data: codeArray[1],
                                                                    success: function () {
                                                                        Taro.showToast({
                                                                            title: '验证码复制成功',
                                                                            icon: 'success',
                                                                        });
                                                                    },
                                                                });
                                                            }}
                                                        >
                                                            验证码: {codeArray[1]}
                                                        </div>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    </SwiperItem>
                                );
                            })}
                        </Swiper>
                        {ticketInfos.length > 1 && (
                            <>
                                <div
                                    className={classNames(styles.actionLeft, {
                                        [styles.disabled]: codeCurrentIndex <= 0,
                                    })}
                                    onClick={() => {
                                        if (codeCurrentIndex <= 0) return;
                                        setCodeCurrentIndex(codeCurrentIndex - 1);
                                    }}
                                ></div>
                                <div
                                    className={classNames(styles.actionRight, {
                                        [styles.disabled]:
                                            codeCurrentIndex >= ticketInfos.length - 1,
                                    })}
                                    onClick={() => {
                                        if (codeCurrentIndex >= ticketInfos.length - 1) return;
                                        setCodeCurrentIndex(codeCurrentIndex + 1);
                                    }}
                                ></div>
                            </>
                        )}
                    </div>
                </div>
            )}
            {/* 订单关闭/ 出票失败 */}
            {[6, 7].includes(detail.orderStatus) && (
                <div className={classNames(styles.card, styles.statusCard)}>
                    <div className={styles.header}>{detail.orderStatusDesc}</div>
                    {detail.orderStatus === 7 ? (
                        <Trash
                            color="var(--color-main)"
                            className={styles.statusImage}
                            size="60px"
                        />
                    ) : (
                        <Refund
                            color="var(--color-main)"
                            className={styles.statusImage}
                            size="60px"
                        />
                    )}
                    {detail.orderStatus === 7 ? (
                        <div className={styles.remarkText}>订单已关闭</div>
                    ) : (
                        <div className={styles.remarkText}>
                            出票失败，付款金额将在24小时内原路退回
                        </div>
                    )}
                    <div className={styles.remarkText}>
                        {showRemark ? '失败原因：' + detail.sellerWords : '如需帮助，请联系客服'}
                    </div>
                </div>
            )}
            {/* 底部 */}
            <div className={styles.card}>
                <div className={styles.header}>金额明细</div>
                <div className={styles.row}>
                    <div className={styles.label}>商品金额</div>
                    <div className={styles.value}>￥{detail.totalPrice}</div>
                </div>
                <div className={styles.row}>
                    <div className={styles.label}></div>
                    <div className={styles.value}>
                        实付款：
                        <span className={styles.paymentAmount}>￥{detail.paymentTotal}</span>
                    </div>
                </div>
                <div className={styles.line}></div>
                <div className={styles.header}>订单信息</div>
                <div className={styles.row}>
                    <div className={styles.label}>订单号</div>
                    <div className={styles.value}>
                        {detail.id}
                        <span
                            className={styles.copy}
                            onClick={() => {
                                Taro.setClipboardData({
                                    data: detail.id,
                                    success: function () {
                                        Taro.showToast({
                                            title: '复制成功',
                                            icon: 'success',
                                        });
                                    },
                                });
                            }}
                        >
                            复制
                        </span>
                    </div>
                </div>
                <div className={styles.row}>
                    <div className={styles.label}>下单时间</div>
                    <div className={styles.value}>{detail.orderTime}</div>
                </div>
                <div className={styles.row}>
                    <div className={styles.label}>订单状态</div>
                    <div className={styles.value}>{detail.orderStatusDesc}</div>
                </div>
                <div className={styles.row}>
                    <div className={styles.label}>购票方式</div>
                    <div className={styles.value}>
                        {TicketModeMap.get(detail.fastTicket ? 1 : (0 as 0 | 1))}
                    </div>
                </div>
                <div className={styles.row}>
                    <div className={styles.label}>自动调座</div>
                    <div className={styles.value}>{detail.switchSeat ? '允许' : '不允许'}</div>
                </div>
                <div className={styles.row}>
                    <div className={styles.label}>购票须知</div>
                    <div className={styles.value}>
                        <span className={styles.colorMain}>不支持退票或改签</span>
                    </div>
                </div>
            </div>
        </div>
    );
};
export default OrderDetailPage;
